package com.springboot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.feign.FoodFeign;
import com.springboot.model.po.Cart;
import com.springboot.model.po.Food;
import com.springboot.service.CartService;
import com.springboot.service.FoodService;

import util.VerifyUtil;

@RefreshScope // 监听动态刷新
@RequestMapping("/carts")
@RestController
public class CartController {
	@Autowired
	CartService cartService;
	@Autowired
	FoodService foodService;
	@Autowired
	private FoodFeign foodFeign;

	@GetMapping
	public ResponseEntity listCart(Cart cart, @RequestParam("token") String token) throws Exception {
		String userId_target = VerifyUtil.verify(token);
		if (userId_target == null || !cart.getUserId().equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");// 401
		}
		// 根据用户id和商家id查询(使用？而不是/，商家编号可以不输入)
		List<Cart> list = cartService.listCart(cart);
		if (list == null || list.size() == 0) {
			return ResponseEntity.status(HttpStatus.NO_CONTENT).body("No Content");//返回204，无内容。
		} else {
			return ResponseEntity.ok(list);
		}
	}
	
	@GetMapping("/getCart/{userId}/{businessId}")//获取当前用户当前商家的购物车信息
	public ResponseEntity getCart(@PathVariable String userId ,@PathVariable int businessId, @RequestParam("token") String token)throws Exception{
		String userId_target = VerifyUtil.verify(token);
		Cart cart =new Cart();
		cart.setBusinessId(businessId);
		cart.setUserId(userId);
		if(userId_target == null || !cart.getUserId().equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");//401
		}
		//根据用户id和商家id查询
		List<Cart> list = cartService.getCart(cart);
		for(int i=0;i<list.size();i++) {
			list.get(i).setFood(foodService.getFoodById(list.get(i).getFoodId()));
		}
		if(list == null || list.size() == 0) {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("The requested resource was not found");
		}else {
			return ResponseEntity.ok(list);
		}
	}

	// 由于传参没有注入，那么这个传递的参数自动从请求头部获取
	@PutMapping
	public ResponseEntity updateCart(@RequestBody Cart cart, @RequestParam String token) throws Exception {
		// foodId , businessId , userId ,quantity(1/-1)
		String userId_target = VerifyUtil.verify(token);
		if (userId_target == null || !cart.getUserId().equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");// 401
		}
		if (cart.getQuantity() > 0)
			cart.setQuantity(cartService.getQuantity(cart) + 1);
		else
			cart.setQuantity(cartService.getQuantity(cart) - 1);
		int result = cartService.updateCart(cart);
		if (result == 0) {
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An internal error occurred");
		} else {
			return ResponseEntity.ok(1);
		}
	}

	@DeleteMapping
	public ResponseEntity removeCart(@RequestBody Cart cart, @RequestParam String token) throws Exception {
		// userId ,businessId,foodId
		String userId_target = VerifyUtil.verify(token);
		if (userId_target == null || !cart.getUserId().equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");// 401
		}
		int result = cartService.removeCart(cart);
		if (result == 0) {
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An internal error occurred");
		} else {
			return ResponseEntity.ok(1);
		}
	}

	// 需要判断food和business的归属问题
	@PostMapping
	public ResponseEntity saveCart(@RequestBody Cart cart, @RequestParam String token) throws Exception {
		// foodId , businessId , userId , quantity = 1
		String userId_target = VerifyUtil.verify(token);
		// 检验foodId和businessId的从属关系
		int foodId = cart.getFoodId();
		Food food = foodService.getFoodById(cart.getFoodId());
		// ResponseEntity<Food> result_ = foodFeign.getFoodById(cart.getFoodId());
		if (!food.getBusinessId().equals(cart.getBusinessId()))
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("WRONG ARGS");// 403
		if (userId_target == null || !cart.getUserId().equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");// 401
		}

		int result = cartService.saveCart(cart);
		if (result == 0) {
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An internal error occurred");
		} else {
			return ResponseEntity.ok(1);
		}
	}

}
